import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:${USER}
 * Date:${YEAR}-${MONTH}-${DAY}
 * ${TIME}
 */
public class Main {
    int[] dx={0,0,1,-1};
    int[] dy={1,-1,0,0};
    boolean[][] visted;
    public int numIslands(char[][] grid) {
        int m=grid.length;int n=grid[0].length;
        visted=new boolean[m][n];
        int count=0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(grid[i][j]=='1'&&visted[i][j]==false){
                    count++;
                    bfs(grid,i,j);
                }
            }
        }
        return count;
    }
    public void bfs(char[][] grid,int i,int j){
        Queue<int[]> queue=new LinkedList<>();
        queue.add(new int[]{i,j});
        visted[i][j]=true;
        while(!queue.isEmpty()){
            int[] tmp=queue.poll();
            int a=tmp[0];int b=tmp[1];

            for(int k=0;k<4;k++){
                int x=a+dx[k];int y=b+dy[k];
                if(x>=0&&x< grid.length&&y>=0&&y<grid[0].length&&visted[x][y]==false&&grid[x][y]=='1'){
                    queue.add(new int[]{x,y});
                    visted[x][y]=true;
                }
            }
        }
    }
}